// admin/system/handler/sys_oper_log_handler.go
package handler

import (
	"go-admin1/admin/system/model"
	"go-admin1/admin/system/service"
	"go-admin1/internal/common/utils"
	"strconv"

	"github.com/gin-gonic/gin"
)

// SysOperLogHandler 操作日志处理器
type SysOperLogHandler struct {
	operLogService service.SysOperLogService
}

// NewSysOperLogHandler 创建操作日志处理器实例
func NewSysOperLogHandler(operLogService service.SysOperLogService) *SysOperLogHandler {
	return &SysOperLogHandler{
		operLogService: operLogService,
	}
}

// Create 创建操作日志
func (h *SysOperLogHandler) Create(c *gin.Context) {
	var operLog model.SysOperLog
	if err := c.ShouldBindJSON(&operLog); err != nil {
		utils.FailResponse[string](c, "参数解析失败: "+err.Error())
		return
	}

	if err := h.operLogService.Create(&operLog); err != nil {
		utils.FailResponse[string](c, "创建操作日志失败: "+err.Error())
		return
	}
	utils.OkResponseNoDataWithMessage[string](c, "创建操作日志成功")
}

// GetByID 根据ID获取操作日志
func (h *SysOperLogHandler) GetByID(c *gin.Context) {
	idStr := c.Param("id")
	id, err := strconv.ParseInt(idStr, 10, 64)
	if err != nil {
		utils.FailResponse[string](c, "参数解析失败: "+err.Error())
		return
	}

	operLog, err := h.operLogService.GetByID(id)
	if err != nil {
		utils.FailResponse[string](c, "获取操作日志失败: "+err.Error())
		return
	}
	utils.OkResponse(c, operLog)
}

// Delete 删除操作日志
func (h *SysOperLogHandler) Delete(c *gin.Context) {
	idStr := c.Param("id")
	id, err := strconv.ParseInt(idStr, 10, 64)
	if err != nil {
		utils.FailResponse[string](c, "参数解析失败: "+err.Error())
		return
	}

	if err := h.operLogService.Delete(id); err != nil {
		utils.FailResponse[string](c, "删除操作日志失败: "+err.Error())
		return
	}
	utils.OkResponseNoDataWithMessage[string](c, "删除操作日志成功")
}

// List 操作日志列表
func (h *SysOperLogHandler) List(c *gin.Context) {
	page, _ := strconv.Atoi(c.DefaultQuery("page", "1"))
	pageSize, _ := strconv.Atoi(c.DefaultQuery("pageSize", "10"))

	operLogs, total, err := h.operLogService.List(page, pageSize)
	if err != nil {
		utils.FailResponse[string](c, "获取操作日志列表失败: "+err.Error())
		return
	}
	resultData := map[string]interface{}{
		"list":  operLogs,
		"total": total,
	}
	utils.OkResponse(c, resultData)
}

// CleanAll 清空操作日志
func (h *SysOperLogHandler) CleanAll(c *gin.Context) {
	if err := h.operLogService.CleanAll(); err != nil {
		utils.FailResponse[string](c, "清空操作日志失败: "+err.Error())
		return
	}
	utils.OkResponseNoDataWithMessage[string](c, "清空操作日志成功")

}
